package com.digital.herbarium.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.digital.herbarium.Entity.*;
import com.digital.herbarium.Exception.CustomException;
import com.digital.herbarium.Mapper.MenuMapper;
import com.digital.herbarium.Mapper.UserMapper;
import com.digital.herbarium.Util.SecuretUtil;
import com.digital.herbarium.Util.TimeUtil;
import com.digital.herbarium.Util.TreeUtil;
import com.digital.herbarium.Util.UserUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServices {

    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    public PageInfo<User> getUserInfo(User user, int pageSize, int pageNum) {
        //return userMapper.getUserInfo(user);
        PageHelper.startPage(pageNum, pageSize);
        List<User> lists = userMapper.getUserInfo(user);
        PageInfo<User> pageInfo = new PageInfo<User>(lists);
        return pageInfo;
    }


    public void addUser(User user) {
        user.setState(1);
        UserUtil.checkUser(user, true);
        UserUtil.checkInfoExist(user, userMapper);
        user.setPassword(SecuretUtil.encrypt(user.getPassword()));
        user.setCreatetime(TimeUtil.getNow());
        userMapper.addUser(user);
        // addRoleMenu(user);

        addUserMenu(user);
        //如果是管理员直接绑定所有菜单
//        if(user.getIsAdmin() == 1){
//            changeToAdmin(user.getUseraccount());
//        }else{
//            addUserMenu(user);
//        }
    }

    public void addUserMenu(User user) {
        //添加关联关系
        String mkey = user.getMenuKey();
        if (!StrUtil.hasEmpty(mkey) && !StrUtil.hasBlank(mkey)) {
            List<UserMenu> ulist = new ArrayList<>();
            String[] strArr = mkey.split(",");
            for (int i = 0; i < strArr.length; i++) {
                UserMenu um = new UserMenu();
                um.setUid(user.getId());
                um.setMkey(strArr[i]);
                ulist.add(um);

            }
            userMapper.batchAddMenu(ulist);
        }
    }

    public void addRoleMenu(User user) {
        //添加关联关系
        if (!StrUtil.hasEmpty(user.getRoleid()) && !StrUtil.hasBlank(user.getRoleid())) {
            List<UserRole> ur = new ArrayList<>();
            String[] strArr = user.getRoleid().split(",");
            for (int i = 0; i < strArr.length; i++) {
                UserRole r = new UserRole();
                r.setUserid(user.getId());
                r.setRoleid(Integer.valueOf(strArr[i]));
                ur.add(r);

            }
            userMapper.bachAdd(ur);
        }
    }

    public void editUser(User user) {
        if (user.getId() == null) {
            throw new CustomException(400, "缺少用户id");
        }
        UserUtil.checkUser(user, false);
        UserUtil.checkEditUserInfo(user, userMapper);
        if(!StrUtil.hasEmpty(user.getPassword()) && !StrUtil.hasBlank(user.getPassword())){
            user.setPassword(SecuretUtil.encrypt(user.getPassword()));
        }

        userMapper.editUser(user);
        //删除关联关系
        userMapper.delUserMenu(user);
        addUserMenu(user);
        //如果是管理员直接绑定所有菜单
//        if(user.getIsAdmin() == 1){
//            changeToAdmin(user.getUseraccount());
//        }else{
//            addUserMenu(user);
//        }

    }


    public void deltUser(String id) {
        if (StrUtil.hasEmpty(id) || StrUtil.hasBlank(id)) {
            throw new CustomException(400, "缺少用户id");
        }
        String[] strArr = id.split(",");
        Long[] ids = Convert.toLongArray(strArr);
        userMapper.delUser(ids);
    }

    public void enableUser(Integer id, Integer state) {
        if (id == null || id == 0) {
            throw new CustomException(400, "缺少用户id");
        }
        UserUtil.checkState(state);
        userMapper.enableUser(id, state);
    }

    public void resetPwd(String useraccount, String password, String pwd) {
        if (useraccount == null || useraccount.equals("")) {
            throw new CustomException(400, "缺少用户账号");
        }
        if (StrUtil.hasEmpty(password) || StrUtil.hasBlank(password)) {
            throw new CustomException(400, "请输入原始密码");
        }

        if (StrUtil.hasEmpty(pwd) || StrUtil.hasBlank(pwd)) {
            throw new CustomException(400, "请输入新密码");
        }

        String encrypt = SecuretUtil.encrypt(pwd);
        User user = new User();
        user.setUseraccount(useraccount);
        List<User> lists = userMapper.getUserInfo(user);
        if(lists.size() == 0){
            throw new CustomException(400, "该用户不存在");
        }
        String oldpwd = SecuretUtil.decrypt(lists.get(0).getPassword());
        if(oldpwd != null && !oldpwd.equals(password)){
            throw new CustomException(400, "原始密码输入错误");
        }


        userMapper.resetPwd(useraccount, encrypt);

    }



    public void resetOldPwd(Integer id, String password) {
        if (id == null || id == 0) {
            throw new CustomException(400, "缺少用户账号");
        }
        if (StrUtil.hasEmpty(password) || StrUtil.hasBlank(password)) {
            throw new CustomException(400, "请输入密码");
        }

        String encrypt = SecuretUtil.encrypt(password);


        userMapper.resetOldPwd(id, encrypt);

    }

    public HashMap<String, Object> login(String useraccount, String password) {
        if (StrUtil.hasEmpty(useraccount) || StrUtil.hasBlank(useraccount)) {
            throw new CustomException(400, "请输入登录账户");
        }
        if (StrUtil.hasEmpty(password) || StrUtil.hasBlank(password)) {
            throw new CustomException(400, "请输入密码");
        }
        String encrypt = SecuretUtil.encrypt(password);
        List<User> user = userMapper.getUser(useraccount, encrypt);
        if (user == null || user.size() == 0) {
            throw new CustomException(400, "用户不存在或者密码错误");
        }
        if (user.get(0).getState() == 0) {
            throw new CustomException(400, "该用户已停用，请通知管理员解锁");
        }
//        String roleid = "";
//        for (int i = 0; i < user.size(); i++) {
//            roleid += user.get(i).getRoleid() + ",";
//        }

        HashMap<String, Object> tokenMap = new HashMap<>();
        String token = jwtTokenUtil.generateToken(useraccount);
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        // 角色信息
//        if (!roleid.equals("null") && !StrUtil.hasEmpty(roleid) && !StrUtil.hasBlank(roleid)) {
//            roleid = roleid.substring(0, roleid.length() - 1);
//            System.out.println("roleid:" + roleid);
//            Long[] ids = Convert.toLongArray(roleid);
//            List<Menu> ms = menuMapper.getMenuByRoleId(ids);
//            user.get(0).setMenuList(ms);
//        }
        List<Menu> menuList = user.get(0).getMenuList();
        List<Map<String, Object>> menuTreeList = new ArrayList<>();

        // 以 parentId 为0的元素为根节点，递归处理子节点
        for (Menu m : menuList) {
            if (m.getParentId() == 0) {
                Map<String, Object>  node = TreeUtil.createNode(m, menuList);
                menuTreeList.add(node);
            }
        }
        user.get(0).setMenuTreeList(menuTreeList);
        tokenMap.put("user", user.get(0));
        return tokenMap;
    }


    public void changeToAdmin(String useraccount) {
        if (StrUtil.hasEmpty(useraccount) || StrUtil.hasBlank(useraccount)) {
            throw new CustomException(400, "请输入账户");
        }
        String[] uas = useraccount.split(",");
        for (int i = 0; i < uas.length; i++) {
            userMapper.changeToAdmin(uas[i]);
            //成为管理员后把所有菜单赋给他
            List<UserMenu> ulist = new ArrayList<>();
            //用户信息
            User user = new User();
            user.setUseraccount(uas[i]);
            List<User> userInfo = userMapper.getUserInfo(user);
            //菜单信息
            if (userInfo.size() > 0) {
                //删除关联关系
                userMapper.delUserMenu(userInfo.get(0));
                List<Menu> menuInfo = menuMapper.getMenuInfo(new Menu());
                for (int j = 0; j < menuInfo.size(); j++) {
                    UserMenu userMenu = new UserMenu();
                    userMenu.setUid(userInfo.get(0).getId());
                    userMenu.setMkey(menuInfo.get(j).getMenuKey());
                    ulist.add(userMenu);
                }
                userMapper.batchAddMenu(ulist);
            }
        }


    }
}
